<?php

namespace app\utils;


class CollectionUtils
{
    protected $_members = [];
    protected $_itemHasType;    //标志是否指定元素的类型
    protected $_itemType;       //集合中的元素类型

    public function __construct($items = [], $itemHasType = false, $itemType = NULL)
    {
        $this->_itemHasType = $itemHasType;
        $this->_itemType = $itemType;
        $tmp = $this->getArrayableItems($items);
        if ($this->_itemHasType) {
            foreach ($tmp as $val) {
                if ($val instanceof $this->_itemType) {
                    $this->_members[] = $val;
                }
            }
        } else {
            $this->_members = $tmp;
        }
    }

    public function addItem($obj)
    {
        if ($this->_itemHasType) {
            if (!($obj instanceof $this->_itemType))
                throw new \Exception("The added obj is not the type of \"$this->_itemType\"!");
        }
        if ($this->exists($obj)) {
            throw new \Exception("Obj is already exists!");
        } else {
            $this->_members[] = $obj;
        }
    }

    public function removeItem($obj)
    {
        if (false != ($key = array_search($obj, $this->_members))) {
            unset($this->_members[$key]);
        } else {
            throw new \Exception("Obj is not exists!");
        }
    }

    public function all()
    {
        return $this->_members;
    }

    public function length()
    {
        return sizeof($this->_members);
    }

    public function exists($obj)
    {
        return in_array($obj, $this->_members);
    }

    protected function getArrayableItems($items)
    {
        if (is_array($items)) {
            return array_values(array_unique($items, SORT_REGULAR));
        } elseif ($items instanceof self) {
            return $items->all();
        }
        return (array) $items;
    }
}
